package com.liujie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liujie.dto.SetmealDto;
import com.liujie.entity.Setmeal;
import com.liujie.entity.SetmealDish;
import com.liujie.mapper.SetmealMapper;
import com.liujie.service.CategoryService;
import com.liujie.service.SetmealDishService;
import com.liujie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    @Override
    public boolean saveWithDish(SetmealDto setmealDto) {
        boolean save = this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        boolean b = setmealDishService.saveBatch(setmealDishes);
        if (save && b){
            return true;
        }
        return false;
    }

    @Override
    public SetmealDto getOneWithDish(long id) {
        SetmealDto setmealDto=new SetmealDto();
        Setmeal setmeal = this.getById(id);
        BeanUtils.copyProperties(setmeal,setmealDto);
        setmealDto.setSetmealDishes(setmealDishService.list(new LambdaQueryWrapper<SetmealDish>().eq(SetmealDish::getSetmealId,id)));
        setmealDto.setCategoryName(categoryService.getById(setmeal.getCategoryId()).getName());
        return setmealDto;
    }

    @Override
    public boolean updateWithDish(SetmealDto setmealDto) {
        boolean b = this.updateById(setmealDto);
        List<SetmealDish> list = setmealDishService.list(new LambdaQueryWrapper<SetmealDish>().eq(SetmealDish::getSetmealId, setmealDto.getId()));//套餐中以前的菜品
        for (SetmealDish setmealDish : list) {
            setmealDishService.removeById(setmealDish);
        }
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();//套餐中现在的菜品
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        boolean b1 = setmealDishService.saveBatch(setmealDishes);
        return b && b1;
    }

    @Override
    public boolean deleteWithDish(long[] ids) {
        boolean b1=false;
        boolean b2=false;
        for (long id : ids) {
            Setmeal setmeal = this.getById(id);
            if (setmeal.getStatus()==0){
                b1 = this.removeById(id);
                b2 = setmealDishService.remove(new LambdaQueryWrapper<SetmealDish>().eq(SetmealDish::getSetmealId, id));
            }
        }
        return b1 && b2;
    }
}
